<?php
// +-----------------------+
// | 注释不留名，代码随便用 |
// +-----------------------+

namespace addons\manager\controller;

use library\Controller;
use think\App;
use think\Db;
use addons\service\AddonsService;
use think\Template;

/**
 * 插件管理
 * Class Plugs
 * @package app\admin\controller
 */
class Plugs extends Controller
{

    public function initialize()
    {
        config('template.view_depr', '.');
        config('template.view_path', dirname(__DIR__) . '/view/');
    }

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'system_plugs';


    /**
     * 列表管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '插件管理';
        return $this->_query($this->table)
            ->page();
    }

    protected function _page_filter(&$data)
    {

        $this->install_statusList = json_decode('["\u672a\u5b89\u88c5","\u5df2\u5b89\u88c5"]', true);/*1*/

    }

    /**
     * 状态开关
     */
    public function switches()
    {
        $vo = Db::name($this->table)->where('id', input('id'))->find();

        if ($vo['install_status']) {
            //如果已安装,则去卸载
            AddonsService::uninstall($vo['name'], $vo['type']);
        } else {
            //去安装
            $data = AddonsService::preload($vo['name']);
            $param = [];
            if (!empty($data['token'])) {
                switch ($data['from']) {
                    case 'gitlab':
                        $param['private_token'] = $data['token'];
                        break;
                    default:
                        $param['access_token'] = $data['token'];
                }
            }
            AddonsService::install($data['name'], $data['file'], $data['type'], $param);
            Db::name($this->table)->where('id', $vo['id'])->update(['install_status' => input('install_status')]);
        }
        Db::name($this->table)->where('id', $vo['id'])->update(['install_status' => input('install_status')]);
        $act = $vo['install_status'] ? '卸载' : '安装';
        $this->success($act . '成功！,请手动刷新浏览器！');
    }


    public function detail()
    {
        if ($this->request->isGet()) {
            return $this->fetch();
        } else {
            $name = $this->request->post('name');
            $type = $this->request->post('type');
            $plugs = \addons\library\Plugs::factory($type, $name);
            $readme_file = $plugs->getLocal() . $name . DIRECTORY_SEPARATOR . 'README.md';
            if (!is_file($readme_file)) {
                $this->error('暂无详情内容！');
            }
            $readme = file_get_contents($readme_file);
            $this->success('详情内容', ['content' => $readme]);
        }
    }


    /**
     * 更新插件
     * @auth true
     */
    public function refresh()
    {
        AddonsService::refresh();
        $this->success('更新成功');
    }
}
